package com.csii.pos.uofplan.service.Impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csii.adhoc.exception.ActSubmitException;
import com.csii.adhoc.exception.ParamValidityException;
import com.csii.adhoc.exception.UidGenerateException;
import com.csii.adhoc.id.UidGenerator;
import com.csii.adhoc.pos.ThinkTime;
import com.csii.pos.activiti.service.ActivitiUofPlanService;
import com.csii.pos.uofplan.UofPlanPo;
import com.csii.pos.uofplan.mapper.UofPlanMapper;
import com.csii.pos.uofplan.service.UofPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.awt.print.PrinterException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("uofPlanService")
@Slf4j
public class UofPlanServiceImpl implements UofPlanService {
    @Resource
    private UofPlanMapper uofPlanMapper;
    @Autowired
    private UidGenerator uidGenerator;
    @Autowired
    private ActivitiUofPlanService activitiUofPlanService;

    private final String FORMAT = "HH:mm:ss";
/**
 * @description: 新增的service层
 * @author liuzhonghua
 * @date  2021.6.23
 * @version 1.0
 */
    @Transactional
    @Override
    public Map addUofPlan(UofPlanPo uofPlanPo)  {
        HashMap<String, Long> map = new HashMap<>();
        //-----------------------  changed by zhanghao  ----------------------------//
        if (StringUtils.isEmpty(uofPlanPo.getUofStartDate())) {
            throw new ParamValidityException("开始日期不能为空!");
        } else if (StringUtils.isEmpty(uofPlanPo.getUofPlanType())) {
            throw new ParamValidityException("计划类型不能为空!");
        } else if (StringUtils.isEmpty(uofPlanPo.getUofPlanItlNo())) {
            throw new ParamValidityException("部门编号不能为空!");
        } else if (StringUtils.isEmpty(uofPlanPo.getUofItemDesc())) {
            throw new ParamValidityException("计划需求说明不能为空!");
        } else if (StringUtils.isEmpty(uofPlanPo.getUofItemAmt())) {
            throw new ParamValidityException("资金需求金额不能为空!");
        }else if (StringUtils.isEmpty(uofPlanPo.getUofEndDate())) {
            throw new ParamValidityException("结束日期不能为空!");
        }
        //生成编号
        long uid = 0;
        try {
            uid = uidGenerator.getUID();
        }catch (UidGenerateException e) {
            log.info("生成主键异常!");
        }

        uofPlanPo.setUofItemSn(uid);

        //设置假数据,这几个字段暂时没有值,但是数据库非空
        uofPlanPo.setPlanStaffNm("null");
        uofPlanPo.setPlanStaffNo("null");
        uofPlanPo.setFlBcpNo("null");
        uofPlanPo.setFlNo("null");
        uofPlanMapper.addUofPlan(uofPlanPo);
        map.put("uofItemSn", uofPlanPo.getUofItemSn());
        return map;
        //-----------------------   change end  ------------------------------------//

        /*//新增返回值
        int i=0;
        //判断时间是否在当前规定区间
        boolean effectiveDate = isEffectiveDate();
//        boolean effectiveDate = true;
        //生成编号
        long uid = uidGenerator.getUID();
        uofPlanPo.setUofItemSn(uid);
        //时间为空则用当前时间
        if (StringUtils.isEmpty(uofPlanPo.getUofPlanDt())){
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
            //当前日期
            String format = df.format(new Date());
            uofPlanPo.setUofPlanDt(format);
        }

        //设置假数据
        uofPlanPo.setPlanStaffNm("1");
        uofPlanPo.setPlanStaffNo("1");
        uofPlanPo.setFlBcpNo("1");
        uofPlanPo.setFlNo("1");
        //是否为紧急计划制定或者集团计划
        if("2".equals(uofPlanPo.getUofPlanFlag())||"3".equals(uofPlanPo.getUofPlanFlag())) {
            i = uofPlanMapper.addUofPlan(uofPlanPo);
            activitiUofPlanService.start(uofPlanPo);
            return i;
        }else {
            //是否为可新增时间
            if (effectiveDate){
                i = uofPlanMapper.addUofPlan(uofPlanPo);
                activitiUofPlanService.start(uofPlanPo);
                return i;
            }else {
                return -1;
            }
        }*/

    }
    /**
     * @description: 删除的service层
     * @author liuzhonghua
     * @date  2021.6.23
     * @version 1.0
     */
    @Override
    public int deleteUofPlan(UofPlanPo uofPlanPo) {
        if (uofPlanPo == null || StringUtils.isEmpty(uofPlanPo.getUofItemSn())) {
            throw new ParamValidityException("资金需求项目序号为空!");
        }
        //-----------------------  changed by zhanghao  ----------------------------//
        //若审批中则不能删除
        String status = uofPlanMapper.findApproveStatus(uofPlanPo.getUofItemSn());

        boolean flag = false;
            if ("1".equals(status)) {
                flag = true;
            }
        if (flag) throw new ActSubmitException("选中的数据包含审批中,无法删除!");
        int rows = uofPlanMapper.deleteUofPlan(uofPlanPo.getUofItemSn());
        activitiUofPlanService.delete(uofPlanPo.getUofItemSn());
        //activitiUofPlanService.delete(uofPlanPo.getUofItemSn().toString());
        return rows;
        //-----------------------   change end  ------------------------------------//

        /*int s = uofPlanMapper.deleteUofPlan(list);
        List<String> strings = stringChange(list);
        activitiUofPlanService.delete(strings);
        return s;*/
    }
    /**
     * @description: 修改的service层
     * @author liuzhonghua
     * @date  2021.6.23
     * @version 1.0
     */
    @Override
    public int updateUofPlan(UofPlanPo uofPlanPo){
        //-----------------------  changed by zhanghao  ----------------------------//
        if (StringUtils.isEmpty(uofPlanPo.getBusnAgrtRst())){
            throw new ParamValidityException("审批状态不能为空");
        } else if (StringUtils.isEmpty(uofPlanPo.getUofItemDesc())) {
            throw new ParamValidityException("描述不能为空");
        } else if (uofPlanPo.getUofItemSn() == null) {
            throw new ParamValidityException("序号不能为空");
        }
        //状态为1-审批中 2-同意 3-拒绝, 则无法更新
        if ("1".equals(uofPlanPo.getBusnAgrtRst()) || "2".equals(uofPlanPo.getBusnAgrtRst()))   throw new ActSubmitException("当前数据已开始审批或审批已结束,无法更新!");

        int rows = uofPlanMapper.updateUofPlan(uofPlanPo);
        return rows;
        //-----------------------   change end  ------------------------------------//

        /*//修改返回值
        int i=0;
        //判断时间是否在当前规定区间
        boolean effectiveDate = isEffectiveDate();
        //时间为空则用当前时间
        if (StringUtils.isEmpty(uofPlanPo.getUofPlanDt())){
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
            //当前日期
            String format = df.format(new Date());
            uofPlanPo.setUofPlanDt(format);
        }
        //是否为紧急计划制定
        if ("2".equals(uofPlanPo.getUofPlanFlag())||"3".equals(uofPlanPo.getUofPlanFlag())) {
            i = uofPlanMapper.updateUofPlan(uofPlanPo);
            return i;
        }else {
            //是否为可修改时间
            if (effectiveDate){
                i = uofPlanMapper.updateUofPlan(uofPlanPo);
            }else {
                return -1;
            }
            return i;
        }*/
    }

    /**
     * @description: 查询的service层
     * @author liuzhonghua
     * @date  2021.6.23
     * @version 1.0
     */
    @Override
    public List<UofPlanPo> queryUofPlan(UofPlanPo uofPlanPo) {

        //-----------------------  changed by zhanghao  ----------------------------//
        if (StringUtils.isEmpty(uofPlanPo.getUofPlanItlNo()) || StringUtils.isEmpty(uofPlanPo.getUofPlanType())) {
            throw new ParamValidityException("部门编号和计划类型都不能为空");
        }

        List<UofPlanPo> uofPlanPoList;
            //周计划查询
            if ("week".equals(uofPlanPo.getUofPlanType())) {
                uofPlanPo.setStartTime(uofPlanPo.getUofStartDate());
                uofPlanPo.setEndTime(uofPlanPo.getUofEndDate());
                uofPlanPoList = uofPlanMapper.queryAllByWeek(uofPlanPo);
            }
            //月计划查询
            else if ("mon".equals(uofPlanPo.getUofPlanType())) {
                //日期格式为 yyyyMMdd, 截取年月。
                String yearAndMonth = uofPlanPo.getUofStartDate().substring(0, 6);
                uofPlanPoList = uofPlanMapper.queryAllByMonth(uofPlanPo, yearAndMonth);
            }
            //临时计划查询
            else if ("tmp".equals(uofPlanPo.getUofPlanType())){
                uofPlanPoList = uofPlanMapper.queryAllByType(uofPlanPo);
            }else {
                throw new ParamValidityException("计划类型不合法");
            }

        return uofPlanPoList;
        //-----------------------   change end  ------------------------------------//


        /*//时间为null用当前时间
         if (StringUtils.isEmpty(uofPlanPo.getUofPlanDt())){
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
            //当前日期
            String format = df.format(new Date());
            uofPlanPo.setUofPlanDt(format);
        }
        String uofPlanDt = uofPlanPo.getUofPlanDt();
        String uofPlanItlNo = uofPlanPo.getUofPlanItlNo();
        String uofPlanFlag = uofPlanPo.getUofPlanFlag();
        String uofItemDesc = null;
        IPage<UofPlanPo> operationLogIPage = uofPlanMapper.queryUofPlan(page,uofPlanDt,uofPlanItlNo,uofPlanFlag,uofItemDesc);
        return operationLogIPage;*/


    }

    /**
     * @description: 查询总金额的service层
     * @author liuzhonghua
     * @date  2021.6.23
     * @version 1.0
     */
    @Override
    public BigDecimal getAllAmtByCondition(UofPlanPo uofPlanPo) {
        //-----------------------  changed by zhanghao  ----------------------------//
        if (StringUtils.isEmpty(uofPlanPo.getUofPlanType())) {
            throw new ParamValidityException("计划类型不能为空");
        }
        if (StringUtils.isEmpty(uofPlanPo.getUofPlanItlNo())) {
            throw new ParamValidityException("部门编号不能为空");
        }
        BigDecimal allAmtByCondition = null;

            //周计划查询
            if ("week".equals(uofPlanPo.getUofPlanType())) {
                uofPlanPo.setStartTime(uofPlanPo.getUofStartDate());
                uofPlanPo.setEndTime(uofPlanPo.getUofEndDate());
                allAmtByCondition = uofPlanMapper.getAllWeekAMT(uofPlanPo);
            }
            //月计划查询
            else if ("mon".equals(uofPlanPo.getUofPlanType())) {
                //日期格式为 yyyyMMdd, 截取年月。
                String yearAndMonth = uofPlanPo.getUofStartDate().substring(0, 6);
                allAmtByCondition = uofPlanMapper.getAllMonthAMT(uofPlanPo, yearAndMonth);
            }
            //临时计划查询
            else {
                allAmtByCondition = uofPlanMapper.getAllAmtByCondition(uofPlanPo);
            }

        return allAmtByCondition;
        //-----------------------   change end  ------------------------------------//

        /*if (StringUtils.isEmpty(uofPlanPo.getUofPlanDt())&&!StringUtils.isEmpty(uofPlanPo.getUofPlanType())) {
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
            //当前日期
            String format = df.format(new Date());
            uofPlanPo.setUofPlanDt(format);
        }
        Double allAmtByCondition = uofPlanMapper.getAllAmtByCondition(uofPlanPo);*/

    }

    /**
     * @description: 查询所有部门的service层
     * @author liuzhonghua
     * @date  2021.6.23
     * @version 1.0
     */
//    @Override
//    public List<UofPlanPo> getAllDepart(String uofPlanItlNo) {
//        if ("005".equals(uofPlanItlNo) || "010".equals(uofPlanItlNo) || StringUtils.isEmpty(uofPlanItlNo)) {
//            List arr = uofPlanMapper.getAllDepart();
//            return arr;
//        }else {
//            List arr = uofPlanMapper.getDepart(uofPlanItlNo);
//            return arr;
//        }
//    }

    @Override
    public List<UofPlanPo> checkPositionPlan(UofPlanPo uofPlanPo) {
        if (StringUtils.isEmpty(uofPlanPo.getUofStartDate())){
            //时间为空则用当前时间
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
                //当前日期
                String format = df.format(new Date());
            uofPlanPo.setUofStartDate(format);
        }
        String uofStartDate = uofPlanPo.getUofStartDate();
        List<String> week = getWeek(uofStartDate);
        uofPlanPo.setStartTime(week.get(0));
        uofPlanPo.setEndTime(week.get(6));
        List<UofPlanPo> list = uofPlanMapper.queryAllByWeek(uofPlanPo);
        return list;
    }

    /**
     * @description: 根据部门编号查询部门名称
     * @author zhanghao
     * @date
     * @version 1.0
     */
    @Override
    public List<UofPlanPo> getDepartName(UofPlanPo uofPlanPo) {
        if (null == uofPlanPo.getUofPlanItlNo() || "".equals(uofPlanPo.getUofPlanItlNo())) {
            throw new ParamValidityException("部门编号不能为空！");
        }
        List<UofPlanPo> departNames = uofPlanMapper.getDepartNames(uofPlanPo.getUofPlanItlNo());

        return departNames;
    }

    @Override
    public UofPlanPo getUofPlan(UofPlanPo uofPlanPo) {
        UofPlanPo uof = uofPlanMapper.getUofPlan(uofPlanPo);
        return uof;
    }

    @Override
    public String findApproveStatus(Long sn) {
        return uofPlanMapper.findApproveStatus(sn);
    }

    /**
     * @description: 判断时间是否在一个区间方法
     * @author liuzhonghua
     * @date
     * @version 1.0
     */
    private boolean isEffectiveDate() {
        SimpleDateFormat df1 = new SimpleDateFormat(FORMAT);//设置日期格式
        String format1 = df1.format(new Date());
        boolean effectiveDate = true;
        try {
            Date nowTime = df1.parse(format1);
            Date startTime = df1.parse("08:30:00");
            Date endTime = df1.parse("16:30:00");
            effectiveDate = ThinkTime.isEffectiveDate(nowTime, startTime, endTime);
        } catch (ParseException e) {
            log.error("日期格式化异常", e);
        }
        return effectiveDate;
    }

    private String uofItemDtChange(String str){
        StringBuffer sb = new StringBuffer();
        String str1;
        char[] chars = str.toCharArray();
        for (int i=0;i<chars.length;i++){
            if (i==4||i==6) {
                sb.append('-');
            }
            sb.append(chars[i]);
        }
        return null;
    }

    /**
     * 根据传入的时间获取当天所在周的全部日期
     * @param oneDay 当天日期
     * @Author: zhanghao
     * @return
     * @throws ParseException
     */
    private List<String> getWeek(String oneDay) {
        //获取日历实例
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            calendar.setTime(sdf.parse(oneDay));
        }catch (Exception e){
            throw new ParamValidityException("日期格式异常");
        }


        /**
         * 设置日历日期为本周的周一
         * 循环取当前的星期和周一做比对，如果不是周一，设置日历往过去推一天，直到设置周一成功
         */
        while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
            calendar.add(Calendar.DAY_OF_MONTH,-1);
        }

        //当前周日期数组
        String[] currentWeekDays = new String[7];

        //日期格式化
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        currentWeekDays[0] = df.format(calendar.getTime());

        for (int i = 1; i < currentWeekDays.length; i++) {
            calendar.add(Calendar.DAY_OF_MONTH,1);
            currentWeekDays[i] = df.format(calendar.getTime());
        }

        return Arrays.asList(currentWeekDays);
    }
}
